﻿using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using UnityEngine;

namespace QFramework
{
    public class CommonData
    {
        public static string StoragePath => Application.streamingAssetsPath + "/Storage/";
        public static string ConfigPath => Application.streamingAssetsPath + "/Config/";
    }
    public class SerializeHelper
    {
        public static T LoadJson<T>(string path)
        {
            // 如果文件存在就加载
            if (File.Exists(path))
            {
                byte[] bytes = File.ReadAllBytes(path);
                if (bytes.Length > 0)
                {
                    string json = Encoding.UTF8.GetString(bytes);
                    return JsonUtility.FromJson<T>(json);
                }
            }
            return default;
        }
        public static void SaveJson<T>(string path, T data)
        {
            var file = new FileInfo(path);
            using (FileStream fs = file.Exists ? file.OpenWrite() : file.Create())
            {
                string json = JsonUtility.ToJson(data);
                byte[] buff = Encoding.UTF8.GetBytes(json);
                fs.Write(buff, 0, buff.Length);
            }
        }
        public static T LoadBinary<T>(string path)
        {
            // 如果文件存在
            if (File.Exists(path))
            {
                //打开一个文件流
                using (FileStream fs = File.Open(path, FileMode.Open))
                {
                    //反序列化方法
                    return (T)new BinaryFormatter().Deserialize(fs);
                }
            }
            return default;
        }
        public static void SaveBinary<T>(string path, T data)
        {
            var file = new FileInfo(path);
            // 如果当前目录存在该文件 打开并写入文件 否则 创建存档文件
            using (FileStream fs = file.Exists ? file.OpenWrite() : file.Create())
            {
                // 将对象序列化为二进制
                new BinaryFormatter().Serialize(fs, data);
            }
        }
    }
}